<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天中心 - 城会玩</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #FF6B35;
            --primary-light: #FF9B6B;
            --primary-dark: #E55A2B;
            --secondary: #2A9D8F;
            --secondary-light: #5ABFAD;
            --light: #F8F9FA;
            --dark: #343A40;
            --dark-light: #495057;
            --accent: #E9C46A;
            --success: #28a745;
            --warning: #ffc107;
            --danger: #dc3545;
            --gray-100: #f8f9fa;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
        }

        * {
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e8ed 100%);
            color: var(--gray-800);
            line-height: 1.6;
            min-height: 100vh;
            margin: 0;
            padding: 0;
        }

        /* 导航栏样式 */
        .navbar-brand {
            font-weight: 700;
            font-size: 1.8rem;
            color: var(--primary) !important;
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            border: none;
            box-shadow: 0 4px 10px rgba(255, 107, 53, 0.3);
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-light), var(--primary));
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(255, 107, 53, 0.4);
        }

        /* 聊天页面容器 */
        .chat-page-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            min-height: calc(100vh - 76px);
        }

        .chat-header-section {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            padding: 25px 30px;
            margin-bottom: 25px;
            position: relative;
            overflow: hidden;
            border: 1px solid rgba(255,255,255,0.8);
        }

        .chat-header-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 5px;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            box-shadow: 0 2px 10px rgba(42, 157, 143, 0.3);
        }

        .page-title {
            font-weight: 800;
            font-size: 2.2rem;
            margin-bottom: 10px;
            color: var(--dark);
            text-shadow: 0 1px 2px rgba(0,0,0,0.05);
        }

        .page-subtitle {
            color: var(--gray-600);
            font-size: 1.1rem;
            margin-bottom: 0;
        }

        /* 聊天主容器 */
        .chat-main-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            overflow: hidden;
            border: 1px solid rgba(255,255,255,0.8);
            height: calc(100vh - 200px);
            min-height: 600px;
        }

        /* 聊天侧边栏 */
        .chat-sidebar {
            height: 100%;
            border-right: 1px solid var(--gray-200);
            background: var(--gray-100);
            display: flex;
            flex-direction: column;
        }

        /* 搜索区域 */
        .search-container {
            padding: 20px;
            border-bottom: 1px solid var(--gray-200);
            background: rgba(255,255,255,0.9);
        }

        .search-input-group {
            position: relative;
        }

        .search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid var(--gray-300);
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            z-index: 1000;
            max-height: 300px;
            overflow-y: auto;
            display: none;
        }

        .search-result-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            border-bottom: 1px solid var(--gray-100);
        }

        .search-result-item:hover {
            background: rgba(255,107,53,0.05);
        }

        .search-result-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 12px;
            border: 2px solid var(--primary-light);
        }

        .search-result-info {
            flex: 1;
        }

        .search-result-name {
            font-weight: 600;
            margin-bottom: 2px;
            color: var(--dark);
        }

        .search-result-bio {
            font-size: 0.85rem;
            color: var(--gray-600);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 聊天列表 */
        .chat-list-container {
            flex: 1;
            overflow-y: auto;
            background: white;
        }

        .chat-list-section {
            border-bottom: 1px solid var(--gray-200);
        }

        .chat-list-header {
            background: rgba(255,255,255,0.9);
            padding: 15px 20px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .chat-list-title {
            font-weight: 600;
            margin-bottom: 0;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .chat-items {
            max-height: 400px;
            overflow-y: auto;
        }

        .chat-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            border-bottom: 1px solid var(--gray-100);
            position: relative;
        }

        .chat-item:hover {
            background: rgba(255,107,53,0.05);
        }

        .chat-item.active {
            background: linear-gradient(90deg, rgba(255,107,53,0.1), transparent);
            border-right: 3px solid var(--primary);
        }

        .chat-item-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 15px;
            border: 2px solid var(--primary-light);
            transition: all 0.3s ease;
        }

        .chat-item:hover .chat-item-avatar {
            transform: scale(1.05);
            box-shadow: 0 4px 10px rgba(0,0,0,0.15);
        }

        .chat-item-info {
            flex: 1;
            min-width: 0;
        }

        .chat-item-name {
            font-weight: 600;
            margin-bottom: 4px;
            color: var(--dark);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-item-last-message {
            font-size: 0.9rem;
            color: var(--gray-600);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-item-meta {
            text-align: right;
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 5px;
        }

        .chat-item-time {
            font-size: 0.8rem;
            color: var(--gray-500);
        }

        .chat-item-badge {
            background: var(--primary);
            color: white;
            border-radius: 10px;
            padding: 3px 8px;
            font-size: 0.75rem;
            min-width: 20px;
            text-align: center;
        }

        .chat-item-status {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: var(--success);
            border: 2px solid white;
            position: absolute;
            bottom: 15px;
            left: 55px;
        }

        .chat-item-status.offline {
            background: var(--gray-400);
        }

        /* 聊天主区域 */
        .chat-main-area {
            height: 100%;
            display: flex;
            flex-direction: column;
            background: linear-gradient(135deg, rgba(255,107,53,0.02), rgba(42,157,143,0.02));
        }

        .chat-area-header {
            padding: 20px 25px;
            border-bottom: 1px solid var(--gray-200);
            background: white;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .chat-header-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .chat-header-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid var(--primary);
        }

        .chat-title-container h4 {
            margin-bottom: 2px;
            color: var(--dark);
            font-weight: 700;
        }

        .chat-subtitle {
            color: var(--gray-600);
            font-size: 0.9rem;
            margin-bottom: 0;
        }

        .chat-header-actions {
            display: flex;
            gap: 10px;
        }

        .chat-messages-area {
            flex: 1;
            padding: 25px;
            overflow-y: auto;
            background: transparent;
        }

        /* 消息样式 */
        .message-group {
            margin-bottom: 20px;
            animation: fadeInUp 0.3s ease;
        }

        .message-group-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;
            padding: 0 10px;
        }

        .message-group-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            object-fit: cover;
        }

        .message-group-sender {
            font-weight: 600;
            font-size: 0.9rem;
            color: var(--dark);
        }

        .message-group-time {
            font-size: 0.8rem;
            color: var(--gray-500);
        }

        .message-group-content {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .message-bubble {
            padding: 12px 16px;
            border-radius: 18px;
            max-width: 100%;
            word-wrap: break-word;
            position: relative;
            animation: messageAppear 0.3s ease;
        }

        @keyframes messageAppear {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message-bubble.own {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: white;
            border-bottom-right-radius: 5px;
            margin-left: auto;
            max-width: 70%;
        }

        .message-bubble.other {
            background: white;
            color: var(--dark);
            border: 1px solid var(--gray-300);
            border-bottom-left-radius: 5px;
            margin-right: auto;
            max-width: 70%;
        }

        .message-bubble.system {
            background: var(--gray-200);
            color: var(--gray-600);
            text-align: center;
            margin: 10px auto;
            max-width: 80%;
            font-size: 0.9rem;
        }

        .message-time {
            font-size: 0.75rem;
            text-align: right;
            margin-top: 5px;
            opacity: 0.7;
        }

        .message-status {
            font-size: 0.7rem;
            margin-top: 2px;
            text-align: right;
            opacity: 0.7;
        }

        /* 输入区域 */
        .chat-input-container {
            padding: 20px 25px;
            border-top: 1px solid var(--gray-200);
            background: white;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
        }

        .input-group {
            gap: 10px;
        }

        .chat-input {
            border-radius: 25px;
            padding: 12px 20px;
            border: 1px solid var(--gray-300);
            resize: none;
            transition: all 0.3s ease;
        }

        .chat-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(255, 107, 53, 0.25);
        }

        .send-button {
            border-radius: 50%;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .send-button:hover {
            transform: scale(1.05);
        }

        /* 空状态 */
        .empty-chat-state {
            text-align: center;
            padding: 80px 20px;
            color: var(--gray-500);
        }

        .empty-chat-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .empty-chat-state h4 {
            margin-bottom: 15px;
            color: var(--gray-600);
            font-weight: 600;
        }

        .empty-chat-state p {
            margin-bottom: 25px;
            font-size: 1.1rem;
        }

        /* 加载状态 */
        .loading-spinner {
            text-align: center;
            padding: 60px 20px;
        }

        .spinner-border {
            width: 3rem;
            height: 3rem;
            border-width: 0.3em;
        }

        /* 消息提示 */
        .alert-message {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            min-width: 300px;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            animation: slideInRight 0.5s ease, fadeOut 0.5s ease 2.5s forwards;
        }

        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        @keyframes fadeOut {
            from { opacity: 1; }
            to { opacity: 0; visibility: hidden; }
        }

        /* 群组信息样式 */
        .group-info-panel {
            background: white;
            border-left: 1px solid var(--gray-200);
            padding: 25px;
            overflow-y: auto;
            display: none;
        }

        .group-info-header {
            text-align: center;
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 1px solid var(--gray-200);
        }

        .group-info-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            margin: 0 auto 15px;
            border: 3px solid var(--primary);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .group-members-list {
            margin-top: 20px;
        }

        .group-member-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            border-radius: 10px;
            margin-bottom: 8px;
            transition: all 0.3s ease;
        }

        .group-member-item:hover {
            background: var(--gray-100);
        }

        .group-member-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 12px;
            border: 2px solid var(--primary-light);
        }

        /* 响应式调整 */
        @media (max-width: 992px) {
            .chat-main-container {
                height: auto;
                min-height: 500px;
            }
            
            .group-info-panel {
                position: fixed;
                top: 0;
                right: 0;
                bottom: 0;
                width: 300px;
                z-index: 1000;
                box-shadow: -5px 0 15px rgba(0,0,0,0.1);
            }
        }

        @media (max-width: 768px) {
            .chat-page-container {
                padding: 15px;
            }
            
            .chat-header-section {
                padding: 20px;
            }
            
            .page-title {
                font-size: 1.8rem;
            }
            
            .chat-main-container {
                border-radius: 15px;
            }
            
            .chat-sidebar {
                position: fixed;
                top: 0;
                left: 0;
                bottom: 0;
                width: 300px;
                z-index: 1000;
                transform: translateX(-100%);
                transition: transform 0.3s ease;
                box-shadow: 5px 0 15px rgba(0,0,0,0.1);
            }
            
            .chat-sidebar.active {
                transform: translateX(0);
            }
            
            .chat-mobile-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 15px 20px;
                border-bottom: 1px solid var(--gray-200);
                background: white;
            }
            
            .mobile-menu-btn {
                display: block;
            }
        }

        @media (max-width: 576px) {
            .chat-page-container {
                padding: 10px;
            }
            
            .chat-header-section {
                padding: 15px;
                border-radius: 15px;
            }
            
            .page-title {
                font-size: 1.6rem;
            }
            
            .chat-messages-area {
                padding: 15px;
            }
            
            .chat-input-container {
                padding: 15px;
            }
            
            .message-bubble.own,
            .message-bubble.other {
                max-width: 85%;
            }
        }

        /* 移动端菜单按钮 */
        .mobile-menu-btn {
            display: none;
            background: none;
            border: none;
            font-size: 1.5rem;
            color: var(--primary);
            cursor: pointer;
        }

        /* 动画效果 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 自定义滚动条 */
        .chat-messages-area::-webkit-scrollbar,
        .chat-items::-webkit-scrollbar,
        .search-results::-webkit-scrollbar {
            width: 6px;
        }

        .chat-messages-area::-webkit-scrollbar-track,
        .chat-items::-webkit-scrollbar-track,
        .search-results::-webkit-scrollbar-track {
            background: var(--gray-100);
        }

        .chat-messages-area::-webkit-scrollbar-thumb,
        .chat-items::-webkit-scrollbar-thumb,
        .search-results::-webkit-scrollbar-thumb {
            background: var(--gray-400);
            border-radius: 3px;
        }

        .chat-messages-area::-webkit-scrollbar-thumb:hover,
        .chat-items::-webkit-scrollbar-thumb:hover,
        .search-results::-webkit-scrollbar-thumb:hover {
            background: var(--gray-500);
        }


        /* 输入指示器样式 */
        .typing-indicator {
            margin: 10px 0;
        }

        .typing-dots {
            display: flex;
            gap: 3px;
        }

        .typing-dots span {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background-color: var(--gray-500);
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-dots span:nth-child(1) { animation-delay: -0.32s; }
        .typing-dots span:nth-child(2) { animation-delay: -0.16s; }

        @keyframes typing {
            0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
            40% { transform: scale(1); opacity: 1; }
        }

        /* 桌面通知样式 */
        .desktop-notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            padding: 15px;
            max-width: 300px;
            z-index: 10000;
            border-left: 4px solid var(--primary);
            animation: slideInRight 0.3s ease;
        }

        .notification-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
        }

        .notification-avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .notification-content {
            font-size: 0.9rem;
            color: var(--gray-700);
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm sticky-top">
        <div class="container">
            <a class="navbar-brand" href="/meet/index/">
                <i class="fas fa-map-marker-alt me-2"></i>城会玩
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/meet/index/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/meet/active/">发现活动</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/meet/create_activity/">创建活动</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/meet/social/">社区</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/user/talking/">聊天</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <a href="/user/person_center/" class="btn btn-outline-primary me-2">
                        <i class="fas fa-user me-2"></i>个人中心
                    </a>
                    <a href="/user/logout/" class="btn btn-outline-primary">
                        <i class="fas fa-sign-out-alt me-2"></i>退出登录
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- 聊天页面内容 -->
    <div class="chat-page-container">
        <!-- 页面标题区域 -->
        <div class="chat-header-section">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="page-title">
                        <i class="fas fa-comments me-3"></i>聊天中心
                    </h1>
                    <p class="page-subtitle">
                        与朋友私聊或加入群组讨论，随时随地保持联系
                    </p>
                </div>
                <div class="col-md-4 text-end">
                    <div class="d-flex gap-3 justify-content-end">
                        <button class="btn btn-primary" onclick="showCreateGroupModal()">
                            <i class="fas fa-plus me-2"></i>创建群组
                        </button>
                        <button class="btn btn-outline-primary mobile-menu-btn" id="mobileMenuBtn">
                            <i class="fas fa-bars"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 聊天主容器 -->
        <div class="chat-main-container">
            <div class="row g-0 h-100">
                <!-- 左侧边栏 -->
                <div class="col-md-4 col-lg-3">
                    <div class="chat-sidebar" id="chatSidebar">
                        <!-- 移动端头部 -->
                        <div class="chat-mobile-header d-md-none">
                            <h5 class="mb-0">聊天列表</h5>
                            <button class="btn-close" id="closeSidebar"></button>
                        </div>

                        <!-- 搜索区域 -->
                        <div class="search-container">
                            <div class="search-input-group">
                                <div class="input-group">
                                    <input type="text" id="user-search-input" class="form-control" placeholder="搜索用户或群组...">
                                    <button class="btn btn-outline-primary" type="button" onclick="searchChatUsers()">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                                <!-- 搜索结果容器 -->
                                <div id="chat-search-results" class="search-results"></div>
                            </div>
                        </div>

                        <!-- 聊天列表 -->
                        <div class="chat-list-container">
                            <!-- 私聊列表 -->
                            <div class="chat-list-section">
                                <div class="chat-list-header">
                                    <h6 class="chat-list-title">
                                        <i class="fas fa-user-friends"></i>私聊
                                        <span class="badge bg-primary" id="private-chat-count">0</span>
                                    </h6>
                                </div>
                                <div id="private-chat-list" class="chat-items">
                                    <div class="loading-spinner">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">加载中...</span>
                                        </div>
                                        <p class="mt-2">加载私聊列表...</p>
                                    </div>
                                </div>
                            </div>

                            <!-- 群聊列表 -->
                            <div class="chat-list-section">
                                <div class="chat-list-header">
                                    <h6 class="chat-list-title">
                                        <i class="fas fa-users"></i>群聊
                                        <span class="badge bg-secondary" id="group-chat-count">0</span>
                                    </h6>
                                </div>
                                <div id="group-chat-list" class="chat-items">
                                    <div class="loading-spinner">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">加载中...</span>
                                        </div>
                                        <p class="mt-2">加载群聊列表...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 中间聊天区域 -->
                <div class="col-md-8 col-lg-6">
                    <div class="chat-main-area">
                        <!-- 聊天头部 -->
                        <div class="chat-area-header">
                            <div class="chat-header-info">
                                <img id="chat-header-avatar" src="" alt="头像" class="chat-header-avatar" style="display: none;">
                                <div class="chat-title-container">
                                    <h4 id="chat-title">选择聊天开始对话</h4>
                                    <p id="chat-subtitle" class="chat-subtitle">与朋友私聊或加入群组讨论</p>
                                </div>
                            </div>
                            <div class="chat-header-actions" id="chat-actions" style="display: none;">
                                <button class="btn btn-sm btn-outline-primary" onclick="toggleGroupInfo()" id="groupInfoBtn" style="display: none;">
                                    <i class="fas fa-info-circle me-1"></i>群组信息
                                </button>
                                <button class="btn btn-sm btn-outline-danger" onclick="clearCurrentChat()" title="清除聊天记录">
                                    <i class="fas fa-trash me-1"></i>清除记录
                                </button>
                            </div>
                        </div>

                        <!-- 消息区域 -->
                        <div class="chat-messages-area" id="chat-messages">
                            <div class="empty-chat-state">
                                <i class="fas fa-comments"></i>
                                <h4>选择一个聊天开始对话</h4>
                                <p class="text-muted">与朋友私聊或加入群组讨论，随时随地保持联系</p>
                                <button class="btn btn-primary" onclick="focusSearch()">
                                    <i class="fas fa-search me-2"></i>搜索用户开始聊天
                                </button>
                            </div>
                            <div id="typing-indicator" class="typing-indicator" style="display: none;">
                                <div class="message-bubble other">
                                    <div class="typing-dots">
                                        <span></span>
                                        <span></span>
                                        <span></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 输入区域 -->
                        <div class="chat-input-container" id="chat-input-container" style="display: none;">
                            <div class="input-group">
                                <textarea class="form-control chat-input" id="chat-message-input" 
                                          placeholder="输入消息..." rows="1"
                                          onkeypress="handleChatInputKeypress(event)"></textarea>
                                <button class="btn btn-primary send-button" type="button" onclick="sendChatMessage()">
                                    <i class="fas fa-paper-plane"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧群组信息面板 -->
                <div class="col-lg-3 d-none d-lg-block">
                    <div class="group-info-panel" id="groupInfoPanel">
                        <div class="group-info-header">
                            <img id="group-info-avatar" src="" alt="群组头像" class="group-info-avatar">
                            <h4 id="group-info-name">群组名称</h4>
                            <p id="group-info-description" class="text-muted">群组描述</p>
                            <div class="d-flex justify-content-center gap-2 mt-3">
                                <span class="badge bg-primary">
                                    <i class="fas fa-users me-1"></i>
                                    <span id="group-member-count">0</span> 成员
                                </span>
                                <span class="badge bg-secondary">
                                    <i class="fas fa-comments me-1"></i>
                                    <span id="group-message-count">0</span> 消息
                                </span>
                            </div>
                        </div>

                        <h6 class="mb-3">群组成员</h6>
                        <div id="group-members-list" class="group-members-list">
                            <!-- 成员列表将通过JavaScript动态加载 -->
                        </div>

                        <div class="mt-4">
                            <button class="btn btn-outline-danger w-100" onclick="leaveCurrentGroup()">
                                <i class="fas fa-sign-out-alt me-2"></i>退出群组
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 消息提示容器 -->
    <div id="message-container"></div>

    <!-- 创建群组模态框 -->
    <div class="modal fade" id="createGroupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">创建新群组</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="create-group-form">
                        <div class="mb-3">
                            <label class="form-label">群组名称</label>
                            <input type="text" class="form-control" name="name" required placeholder="请输入群组名称" maxlength="50">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">群组描述</label>
                            <textarea class="form-control" name="description" rows="3" placeholder="请输入群组描述" maxlength="200"></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">最大成员数</label>
                            <input type="number" class="form-control" name="max_members" value="50" min="2" max="500">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="createGroup()">创建群组</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentUser = {
            id: parseInt('{{ user.id }}') || 0,
            username: '{{ user.username }}' || '用户',
            avatar: '{{ user.avatar.url }}' || '/media/avatars/default.png'
        };
        // 全局变量
        let currentChat = {
            type: null,      // 'private' 或 'group'
            targetId: null,
            targetName: null,
            targetAvatar: null
        };

        let chatData = {
            privateChats: [],
            groupChats: []
        };

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeChatPage();
        });

        /**
         * 初始化聊天页面
         */
        function initializeChatPage() {
            // 加载聊天列表
            loadChatLists();
            
            // 设置移动端菜单
            setupMobileMenu();
            
            // 设置自动刷新
            setInterval(loadChatLists, 30000); // 每30秒刷新一次聊天列表
            
            // 设置消息输入框自动调整高度
            setupMessageInput();
            setupAvatarErrorHandling();
        }

        /**
         * 设置移动端菜单功能
         */
        function setupMobileMenu() {
            const mobileMenuBtn = document.getElementById('mobileMenuBtn');
            const closeSidebar = document.getElementById('closeSidebar');
            const chatSidebar = document.getElementById('chatSidebar');
            
            if (mobileMenuBtn && closeSidebar && chatSidebar) {
                mobileMenuBtn.addEventListener('click', function() {
                    chatSidebar.classList.add('active');
                });
                
                closeSidebar.addEventListener('click', function() {
                    chatSidebar.classList.remove('active');
                });
            }
        }

        /**
         * 设置消息输入框自动调整高度
         */
        function setupMessageInput() {
            const messageInput = document.getElementById('chat-message-input');
            if (messageInput) {
                messageInput.addEventListener('input', function() {
                    this.style.height = 'auto';
                    this.style.height = (this.scrollHeight) + 'px';
                });
            }
        }

        /**
         * 处理聊天输入框按键事件
         */
        function handleChatInputKeypress(event) {
            if (event.keyCode === 13 && !event.shiftKey) {
                event.preventDefault();
                sendChatMessage();
            }
        }

        /**
         * 加载聊天列表
         */
        async function loadChatLists() {
            try {
                console.log('开始加载聊天列表...');
                const response = await fetch('/user/section_data/private-messages/');

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                console.log('收到聊天数据:', data);

                if (data.success) {
                    if (data.chat_groups) {
                        chatData.groupChats = data.chat_groups;
                        renderGroupChatList(chatData.groupChats);
                    }

                    if (data.recent_messages) {
                        chatData.privateChats = data.recent_messages;
                        renderPrivateChatList(chatData.privateChats);
                    }

                    // 更新未读消息计数
                    updateUnreadCounts();
                } else {
                    console.error('API返回失败:', data.message);
                    showMessage('加载聊天列表失败: ' + (data.message || '未知错误'), 'error');
                }

            } catch (error) {
                console.error('加载聊天列表失败:', error);
                showMessage('加载聊天列表失败: ' + error.message, 'error');

                // 显示错误状态
                showChatListError();
            }
        }

        /**
         * 显示聊天列表错误状态
         */
        function showChatListError() {
            const privateContainer = document.getElementById('private-chat-list');
            const groupContainer = document.getElementById('group-chat-list');

            const errorHTML = `
                <div class="text-center py-4 text-muted">
                    <i class="fas fa-exclamation-triangle fa-2x mb-3"></i>
                    <p>加载失败</p>
                    <button class="btn btn-sm btn-outline-primary mt-2" onclick="loadChatLists()">
                        重试
                    </button>
                </div>
            `;

            if (privateContainer) privateContainer.innerHTML = errorHTML;
            if (groupContainer) groupContainer.innerHTML = errorHTML;
        }

        /**
 * HTML 转义函数
 */
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

        /**
         * 渲染私聊列表
         */
function renderPrivateChatList(chats) {
    const container = document.getElementById('private-chat-list');
    const countElement = document.getElementById('private-chat-count');

    if (!container) return;

    if (!chats || chats.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="fas fa-user-friends fa-2x mb-3"></i>
                <p>暂无私聊记录</p>
                <small>搜索用户开始聊天</small>
            </div>
        `;
        if (countElement) countElement.textContent = '0';
        return;
    }

    let html = '';
    chats.forEach(chat => {
        // 确保数据完整性
        const avatar = getSafeAvatarUrl(chat.avatar, false);
        const username = chat.username || '未知用户';
        const lastMessage = chat.last_message || '暂无消息';
        const lastMessageTime = chat.last_message_time ? formatMessageTime(chat.last_message_time) : '';
        const unreadCount = chat.unread_count || 0;

        html += `
            <div class="chat-item" onclick="openChat('private', ${chat.user_id}, '${escapeHtml(username)}', '${escapeHtml(avatar)}')">
                <img src="${escapeHtml(avatar)}" alt="用户头像" class="chat-item-avatar"
                    onerror="this.src='/static/images/default-avatar.png'">
                <div class="chat-item-info">
                    <div class="chat-item-name">${escapeHtml(username)}</div>
                    <div class="chat-item-last-message">${escapeHtml(lastMessage)}</div>
                </div>
                <div class="chat-item-meta">
                    <div class="chat-item-time">${lastMessageTime}</div>
                    ${unreadCount > 0 ? `
                        <span class="chat-item-badge">${unreadCount}</span>
                    ` : ''}
                </div>
                <div class="chat-item-status ${Math.random() > 0.3 ? '' : 'offline'}"></div>
            </div>
        `;
    });

    container.innerHTML = html;
    if (countElement) countElement.textContent = chats.length;
}

        /**
         * 渲染群聊列表
         */
        function renderGroupChatList(groups) {
            const container = document.getElementById('group-chat-list');
            const countElement = document.getElementById('group-chat-count');

            if (!groups || groups.length === 0) {
                container.innerHTML = `
                    <div class="text-center py-4 text-muted">
                        <i class="fas fa-users fa-2x mb-3"></i>
                        <p>暂无群聊记录</p>
                    </div>
                `;
                if (countElement) countElement.textContent = '0';
                return;
            }

            let html = '';
            groups.forEach(group => {
                const avatar = getSafeAvatarUrl(group.avatar, true);
                const lastMessage = group.last_message || '暂无消息';
                const lastMessageTime = group.last_message_time ? formatMessageTime(group.last_message_time) : '';
                const unreadCount = group.unread_count || 0;

                html += `
                    <div class="chat-item" onclick="openChat('group', ${group.id}, '${escapeHtml(group.name)}', '${escapeHtml(avatar)}')">
                        <img src="${escapeHtml(avatar)}" alt="群组头像" class="chat-item-avatar"
                            onerror="this.src='/static/images/default-group-avatar.png'">
                        <div class="chat-item-info">
                            <div class="chat-item-name">
                                ${escapeHtml(group.name)}
                                ${group.is_owner ? '<i class="fas fa-crown text-warning ms-1" title="群主"></i>' : ''}
                            </div>
                            <div class="chat-item-last-message">${escapeHtml(lastMessage)}</div>
                        </div>
                        <div class="chat-item-meta">
                            <div class="chat-item-time">${lastMessageTime}</div>
                            ${unreadCount > 0 ? `
                                <span class="chat-item-badge">${unreadCount}</span>
                            ` : ''}
                        </div>
                    </div>
                `;
            });

            container.innerHTML = html;
            if (countElement) countElement.textContent = groups.length;
        }

        /**
         * 打开聊天
         */
        function openChat(chatType, targetId, targetName, targetAvatar) {
            console.log('打开聊天:', chatType, targetId, targetName);

            currentChat = { type: chatType, targetId: targetId, targetName: targetName, targetAvatar: targetAvatar };

            // 更新UI状态
            document.querySelectorAll('.chat-item').forEach(item => item.classList.remove('active'));
            event.currentTarget.classList.add('active');

            // 更新聊天标题
            document.getElementById('chat-title').textContent = targetName;
            document.getElementById('chat-subtitle').textContent = chatType === 'private' ? '私聊' : `群聊 • ${getGroupMemberCount()}人在线`;

            // 更新头像
            const headerAvatar = document.getElementById('chat-header-avatar');
            if (targetAvatar) {
                headerAvatar.src = getSafeAvatarUrl(targetAvatar, chatType === 'group');
                headerAvatar.style.display = 'block';
            } else {
                headerAvatar.style.display = 'none';
            }

            // 显示聊天操作按钮
            document.getElementById('chat-actions').style.display = 'flex';

            // 显示群组信息按钮（如果是群聊）
            const groupInfoBtn = document.getElementById('groupInfoBtn');
            groupInfoBtn.style.display = chatType === 'group' ? 'block' : 'none';

            // 显示输入框
            document.getElementById('chat-input-container').style.display = 'block';

            // 隐藏移动端侧边栏
            document.getElementById('chatSidebar').classList.remove('active');

            // 加载聊天历史
            loadChatHistory();

            // 如果是群聊，加载群组信息
            if (chatType === 'group') {
                loadGroupInfo(targetId);
            } else {
                hideGroupInfo();
            }
        }

        /**
         * 加载聊天历史
         */
        async function loadChatHistory() {
    if (!currentChat.targetId) return;

    try {
        let url = '';
        if (currentChat.type === 'private') {
            url = `/user/get_private_chat_history/?target_id=${currentChat.targetId}&limit=50`;
        } else if (currentChat.type === 'group') {
            url = `/user/get_group_chat_history/?group_id=${currentChat.targetId}&limit=50`;
        }

        console.log('正在加载聊天历史:', url);

        const response = await fetch(url);
        const result = await response.json();

        if (result.success) {
            console.log('收到历史消息:', result.messages);
            renderChatMessages(result.messages);

            // 滚动到底部
            setTimeout(() => {
                const messagesContainer = document.getElementById('chat-messages');
                if (messagesContainer) {
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                }
            }, 100);
        } else {
            console.error('加载历史消息失败:', result.message);
            showMessage('加载历史消息失败: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('加载历史消息失败:', error);
        showMessage('加载历史消息失败，请检查网络连接', 'error');
    }
}

        /**
         * 渲染聊天消息
         */
        function renderChatMessages(messages) {
            const messagesContainer = document.getElementById('chat-messages');
            
            if (!messages || messages.length === 0) {
                messagesContainer.innerHTML = `
                    <div class="empty-chat-state">
                        <i class="fas fa-comment-slash"></i>
                        <h4>还没有消息</h4>
                        <p class="text-muted">发送第一条消息开始对话吧！</p>
                    </div>
                `;
                return;
            }
            
            let html = '';
            let lastSenderId = null;
            let lastMessageTime = null;
            
            messages.forEach(message => {
                const messageTime = new Date(message.created_at);
                const isNewDay = !lastMessageTime || 
                                messageTime.toDateString() !== lastMessageTime.toDateString();
                
                // 显示日期分隔符
                if (isNewDay) {
                    html += `
                        <div class="text-center my-4">
                            <span class="badge bg-light text-dark">
                                ${formatMessageDate(messageTime)}
                            </span>
                        </div>
                    `;
                }
                
                const isSameSender = lastSenderId === message.sender_id;
                const timeDiff = lastMessageTime ? 
                    (messageTime - lastMessageTime) / 60000 : 30; // 分钟
                
                // 添加发送者信息（如果不是连续发送）
                if (!isSameSender || timeDiff > 5 || isNewDay) {
                    if (currentChat.type === 'group' && !message.is_own) {
                        html += `
                            <div class="message-group-header">
                                <img src="${message.sender_avatar}" alt="头像" class="message-group-avatar"
                                    onerror="this.src='https://res.cloudinary.com/dqfqah1dn/image/upload/meetlocal/avatars/default.png'">
                                <span class="message-group-sender">${message.sender_name}</span>
                                <span class="message-group-time">${formatMessageTime(message.created_at)}</span>
                            </div>
                        `;
                    }
                }
                
                // 消息气泡
                html += `
                    <div class="message-bubble ${message.is_own ? 'own' : 'other'}">
                        ${message.content}
                    </div>
                `;
                
                lastSenderId = message.sender_id;
                lastMessageTime = messageTime;
            });
            
            messagesContainer.innerHTML = html;
            
            // 滚动到底部
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        /**
 * 安全的头像URL处理
 */
function getSafeAvatarUrl(avatarUrl, isGroup = false) {
    if (!avatarUrl || avatarUrl === 'null' || avatarUrl === 'undefined') {
        return isGroup ? '/static/images/default-group-avatar.png' : '/static/images/default-avatar.png';
    }

    // 如果已经是完整URL，直接返回
    if (avatarUrl.startsWith('http')) {
        return avatarUrl;
    }

    // 如果是相对路径，确保以/开头
    if (avatarUrl.startsWith('/media/') || avatarUrl.startsWith('/static/')) {
        return avatarUrl;
    }

    // 处理Cloudinary路径
    if (avatarUrl.includes('cloudinary')) {
        return avatarUrl;
    }

    // 默认头像回退
    return isGroup ? '/static/images/default-group-avatar.png' : '/static/images/default-avatar.png';
}

/**
 * 修复头像加载错误处理
 */
function setupAvatarErrorHandling() {
    document.addEventListener('DOMContentLoaded', function() {
        // 为所有头像图片添加错误处理
        document.addEventListener('error', function(e) {
            if (e.target.tagName === 'IMG') {
                if (e.target.classList.contains('chat-item-avatar') ||
                    e.target.classList.contains('search-result-avatar') ||
                    e.target.classList.contains('message-group-avatar')) {
                    e.target.src = '/static/images/default-avatar.png';
                } else if (e.target.classList.contains('group-info-avatar') ||
                          e.target.id === 'group-info-avatar' ||
                          e.target.classList.contains('group-member-avatar')) {
                    e.target.src = '/static/images/default-group-avatar.png';
                }
            }
        }, true);
    });
}

        /**
         * 搜索聊天用户
         */
        async function searchChatUsers() {
            const searchInput = document.getElementById('user-search-input');
            const query = searchInput.value.trim();
            const resultsContainer = document.getElementById('chat-search-results');
            
            if (!query) {
                resultsContainer.style.display = 'none';
                showMessage('请输入搜索关键词', 'warning');
                return;
            }
            
            resultsContainer.innerHTML = `
                <div class="text-center py-3">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">搜索中...</span>
                    </div>
                    <p class="mt-2">正在搜索用户...</p>
                </div>
            `;
            resultsContainer.style.display = 'block';
            
            try {
                const response = await fetch('/user/search_users/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify({ query: query })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    renderChatSearchResults(result.users);
                } else {
                    resultsContainer.innerHTML = `
                        <div class="alert alert-warning text-center m-2">
                            <i class="fas fa-exclamation-triangle me-2"></i>${result.message}
                        </div>
                    `;
                }
            } catch (error) {
                console.error('搜索失败:', error);
                resultsContainer.innerHTML = `
                    <div class="alert alert-danger text-center m-2">
                        <i class="fas fa-exclamation-triangle me-2"></i>搜索失败，请重试
                    </div>
                `;
            }
        }

        /**
         * 渲染聊天搜索结果
         */
        function renderChatSearchResults(users) {
            const resultsContainer = document.getElementById('chat-search-results');
            
            if (!users || users.length === 0) {
                resultsContainer.innerHTML = `
                    <div class="text-center py-4 text-muted">
                        <i class="fas fa-search fa-2x mb-3"></i>
                        <p>未找到用户</p>
                    </div>
                `;
                return;
            }
            
            let html = '';
            users.forEach(user => {
                html += `
                    <div class="search-result-item" onclick="startPrivateChat(${user.id}, '${user.username}', '${user.avatar}')">
                        <img src="${user.avatar}" alt="用户头像" class="search-result-avatar"
                            onerror="this.src='https://res.cloudinary.com/dqfqah1dn/image/upload/meetlocal/avatars/default.png'">
                        <div class="search-result-info">
                            <div class="search-result-name">${user.username}</div>
                            <div class="search-result-bio">${user.bio || '这个用户很懒，还没有写个人简介...'}</div>
                        </div>
                    </div>
                `;
            });
            
            resultsContainer.innerHTML = html;
        }

        /**
         * 开始私聊
         */
        function startPrivateChat(userId, username, avatar) {
            // 隐藏搜索结果
            document.getElementById('chat-search-results').style.display = 'none';
            
            // 清空搜索框
            document.getElementById('user-search-input').value = '';
            
            // 打开聊天
            openChat('private', userId, username, avatar);
        }

        /**
         * 显示创建群组模态框
         */
        function showCreateGroupModal() {
            const modal = new bootstrap.Modal(document.getElementById('createGroupModal'));
            modal.show();
        }

        /**
         * 创建群组
         */
        async function createGroup() {
            const form = document.getElementById('create-group-form');
            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());
            
            try {
                const response = await fetch('/user/create_chat_group/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage('群组创建成功', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('createGroupModal')).hide();
                    // 重新加载聊天列表
                    loadChatLists();
                } else {
                    showMessage('创建失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('创建群组失败:', error);
                showMessage('创建失败，请重试', 'error');
            }
        }

        /**
         * 加载群组信息
         */
        async function loadGroupInfo(groupId) {
            try {
                const response = await fetch(`/user/get_group_info/?group_id=${groupId}`);
                const result = await response.json();
                
                if (result.success) {
                    renderGroupInfo(result.group);
                    showGroupInfo();
                }
            } catch (error) {
                console.error('加载群组信息失败:', error);
            }
        }

        /**
         * 渲染群组信息
         */
        function renderGroupInfo(group) {
            document.getElementById('group-info-avatar').src = group.avatar;
            document.getElementById('group-info-name').textContent = group.name;
            document.getElementById('group-info-description').textContent = group.description || '暂无描述';
            document.getElementById('group-member-count').textContent = group.member_count;
            document.getElementById('group-message-count').textContent = group.message_count;
            
            // 渲染成员列表
            const membersList = document.getElementById('group-members-list');
            let html = '';
            group.members.forEach(member => {
                html += `
                    <div class="group-member-item">
                        <img src="${member.avatar}" alt="成员头像" class="group-member-avatar"
                            onerror="this.src='https://res.cloudinary.com/dqfqah1dn/image/upload/meetlocal/avatars/default.png'">
                        <div class="flex-grow-1">
                            <div class="fw-bold">${member.username}</div>
                            <small class="text-muted">${member.role === 'owner' ? '群主' : member.role === 'admin' ? '管理员' : '成员'}</small>
                        </div>
                        ${member.role === 'owner' ? '<i class="fas fa-crown text-warning"></i>' : ''}
                    </div>
                `;
            });
            membersList.innerHTML = html;
        }

        /**
         * 切换群组信息面板显示
         */
        function toggleGroupInfo() {
            const panel = document.getElementById('groupInfoPanel');
            if (panel.style.display === 'block') {
                hideGroupInfo();
            } else {
                showGroupInfo();
            }
        }

        /**
         * 显示群组信息
         */
        function showGroupInfo() {
            document.getElementById('groupInfoPanel').style.display = 'block';
        }

        /**
         * 隐藏群组信息
         */
        function hideGroupInfo() {
            document.getElementById('groupInfoPanel').style.display = 'none';
        }

        /**
         * 退出当前群组
         */
        async function leaveCurrentGroup() {
            if (!currentChat.targetId || currentChat.type !== 'group') {
                showMessage('请先选择群组', 'warning');
                return;
            }
            
            if (!confirm('确定要退出这个群组吗？退出后将无法接收群组消息。')) {
                return;
            }
            
            try {
                const response = await fetch('/user/leave_group/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify({
                        group_id: currentChat.targetId
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage(result.message, 'success');
                    // 重置当前聊天
                    resetCurrentChat();
                    // 重新加载聊天列表
                    loadChatLists();
                    // 隐藏群组信息
                    hideGroupInfo();
                } else {
                    showMessage('退出失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('退出群组失败:', error);
                showMessage('退出失败，请重试', 'error');
            }
        }

        /**
         * 清除当前聊天记录
         */
        async function clearCurrentChat() {
            if (!currentChat.targetId) {
                showMessage('请先选择聊天', 'warning');
                return;
            }
            
            if (!confirm('确定要清除聊天记录吗？此操作将标记消息为已读，但不会删除实际消息。')) {
                return;
            }
            
            try {
                const response = await fetch('/user/clear_chat_history/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    body: JSON.stringify({
                        type: currentChat.type,
                        target_id: currentChat.targetId
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage(result.message, 'success');
                    // 重新加载消息
                    loadChatHistory();
                    // 刷新聊天列表
                    loadChatLists();
                } else {
                    showMessage('清除失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('清除聊天记录失败:', error);
                showMessage('清除失败，请重试', 'error');
            }
        }

        /**
         * 标记消息为已读
         */
        async function markMessagesAsRead() {
            // 这里可以实现标记消息为已读的逻辑
            // 具体实现取决于后端API
        }

        /**
         * 更新未读消息计数
         */
        function updateUnreadCounts() {
            // 更新页面标题的未读计数
            let totalUnread = 0;
            chatData.privateChats.forEach(chat => {
                totalUnread += chat.unread_count || 0;
            });
            chatData.groupChats.forEach(group => {
                totalUnread += group.unread_count || 0;
            });
            
            if (totalUnread > 0) {
                document.title = `(${totalUnread}) 聊天中心 - 城会玩`;
            } else {
                document.title = '聊天中心 - 城会玩';
            }
        }

        /**
         * 重置当前聊天状态
         */
        function resetCurrentChat() {
            currentChat = { type: null, targetId: null, targetName: null, targetAvatar: null };
            
            document.getElementById('chat-title').textContent = '选择聊天开始对话';
            document.getElementById('chat-subtitle').textContent = '与朋友私聊或加入群组讨论';
            document.getElementById('chat-header-avatar').style.display = 'none';
            document.getElementById('chat-actions').style.display = 'none';
            document.getElementById('chat-input-container').style.display = 'none';
            document.getElementById('chat-messages').innerHTML = `
                <div class="empty-chat-state">
                    <i class="fas fa-comments"></i>
                    <h4>选择一个聊天开始对话</h4>
                    <p class="text-muted">与朋友私聊或加入群组讨论，随时随地保持联系</p>
                    <button class="btn btn-primary" onclick="focusSearch()">
                        <i class="fas fa-search me-2"></i>搜索用户开始聊天
                    </button>
                </div>
            `;
        }

        /**
         * 聚焦搜索框
         */
        function focusSearch() {
            document.getElementById('user-search-input').focus();
            // 在移动端显示侧边栏
            document.getElementById('chatSidebar').classList.add('active');
        }

        /**
         * 获取群组成员数量（模拟）
         */
        function getGroupMemberCount() {
            return Math.floor(Math.random() * 20) + 5; // 模拟5-25人在线
        }

        /**
         * 格式化消息时间
         */
        function formatMessageTime(timeString) {
            if (!timeString) return '';
            
            const messageTime = new Date(timeString);
            const now = new Date();
            const diffMs = now - messageTime;
            const diffMins = Math.floor(diffMs / 60000);
            const diffHours = Math.floor(diffMs / 3600000);
            const diffDays = Math.floor(diffMs / 86400000);
            
            if (diffMins < 1) {
                return '刚刚';
            } else if (diffMins < 60) {
                return `${diffMins}分钟前`;
            } else if (diffHours < 24) {
                return `${diffHours}小时前`;
            } else if (diffDays < 7) {
                return `${diffDays}天前`;
            } else {
                return messageTime.toLocaleDateString('zh-CN', {
                    month: 'short',
                    day: 'numeric'
                });
            }
        }

        /**
         * 格式化消息日期
         */
        function formatMessageDate(date) {
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            
            if (date.toDateString() === today.toDateString()) {
                return '今天';
            } else if (date.toDateString() === yesterday.toDateString()) {
                return '昨天';
            } else {
                return date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
            }
        }

        /**
         * 显示消息提示
         */
        function showMessage(message, type = 'info') {
            const messageContainer = document.getElementById('message-container');
            
            const alertClass = {
                'success': 'alert-success',
                'error': 'alert-danger',
                'warning': 'alert-warning',
                'info': 'alert-info'
            }[type] || 'alert-info';
            
            const iconClass = {
                'success': 'fa-check-circle',
                'error': 'fa-exclamation-circle',
                'warning': 'fa-exclamation-triangle',
                'info': 'fa-info-circle'
            }[type] || 'fa-info-circle';
            
            const alert = document.createElement('div');
            alert.className = `alert ${alertClass} alert-dismissible fade show alert-message`;
            alert.innerHTML = `
                <i class="fas ${iconClass} me-2"></i>
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            messageContainer.appendChild(alert);
            
            // 自动移除消息
            setTimeout(() => {
                if (alert.parentNode) {
                    alert.parentNode.removeChild(alert);
                }
            }, 3000);
        }

        /**
         * 获取CSRF token
         */
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }



// WebSocket连接状态管理
let chatSocket = null;
let isConnecting = false;
let reconnectTimer = null;

/**
 * 连接 WebSocket
 */
function connectWebSocket() {
    if (isConnecting) return;

    isConnecting = true;
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/ws/chat/`;

    console.log('正在连接 WebSocket:', wsUrl);

    try {
        chatSocket = new WebSocket(wsUrl);

        chatSocket.onopen = function(e) {
            console.log('WebSocket 连接成功');
            isConnecting = false;
            reconnectAttempts = 0;

            // 发送认证信息
            if (currentUser && currentUser.id) {
                const authData = {
                    'type': 'auth',
                    'user_id': currentUser.id
                };
                chatSocket.send(JSON.stringify(authData));
            }
            showMessage('实时连接已建立', 'success');
        };

        chatSocket.onclose = function(e) {
            console.log('WebSocket 连接关闭:', e.code, e.reason);
            isConnecting = false;

            // 自动重连逻辑
            if (reconnectAttempts < maxReconnectAttempts) {
                const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
                console.log(`将在 ${delay}ms 后重连...`);

                reconnectTimer = setTimeout(() => {
                    reconnectAttempts++;
                    connectWebSocket();
                }, delay);
            }
        };

        chatSocket.onerror = function(e) {
            console.error('WebSocket 发生错误:', e);
            isConnecting = false;
            showMessage('连接错误，将自动重连', 'warning');
        };

        chatSocket.onmessage = function(e) {
            try {
                const data = JSON.parse(e.data);
                console.log('收到 WebSocket 消息:', data);
                handleWebSocketMessage(data);
            } catch (error) {
                console.error('解析 WebSocket 消息失败:', error);
            }
        };

    } catch (error) {
        console.error('创建 WebSocket 连接失败:', error);
        isConnecting = false;
        showMessage('连接失败: ' + error.message, 'error');
    }
}

/**
 * 检查WebSocket连接状态
 */
function checkWebSocketConnection() {
    if (!chatSocket || chatSocket.readyState !== WebSocket.OPEN) {
        console.warn('WebSocket 未就绪，状态:', chatSocket ? chatSocket.readyState : '未初始化');
        return false;
    }
    return true;
}

/**
 * 处理 WebSocket 消息
 */
function handleWebSocketMessage(data) {
    switch (data.type) {
        case 'private_message':
        case 'group_message':
            handleNewMessage(data);
            break;
        case 'typing_indicator':
            handleTypingIndicator(data);
            break;
        case 'read_receipt':
            handleReadReceipt(data);
            break;
        case 'user_status':
            handleUserStatus(data);
            break;
        case 'auth_success':
            console.log('WebSocket 认证成功');
            break;
        case 'error':
            showMessage(data.message, 'error');
            break;
        default:
            console.log('未知消息类型:', data.type, data);
    }
}

/**
 * 处理新消息
 */
function handleNewMessage(message) {
    console.log('处理新消息:', message);

    // 检查是否应该在当前聊天界面显示这条消息
    if (shouldDisplayMessage(message)) {
        appendMessageToChat(message);

        // 发送已读回执
        if (!message.is_own) {
            sendReadReceipt(message.message_id, message.type.replace('_message', ''));
        }

        // 滚动到底部
        setTimeout(() => {
            const messagesContainer = document.getElementById('chat-messages');
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }, 100);
    }

    // 更新聊天列表
    updateChatListWithNewMessage(message);

    // 显示桌面通知（如果不在当前聊天）
    if (!isCurrentChatActive(message) && !message.is_own) {
        showDesktopNotification(message);
    }
}

/**
 * 更新聊天列表中的新消息
 */
function updateChatListWithNewMessage(message) {
    // 这里可以实现更新聊天列表的未读计数等功能
    console.log('更新聊天列表:', message);
}

/**
 * 显示桌面通知
 */
function showDesktopNotification(message) {
    if (!("Notification" in window)) return;

    if (Notification.permission === "granted") {
        const notification = new Notification(`${message.sender_name}`, {
            body: message.content,
            icon: message.sender_avatar || '/static/images/default-avatar.png'
        });

        notification.onclick = function() {
            window.focus();
            notification.close();
        };
    }
}

/**
 * 检查当前聊天是否活跃
 */
function isCurrentChatActive(message) {
    return document.visibilityState === 'visible' &&
           shouldDisplayMessage(message);
}

/**
 * 判断是否应该显示消息
 */
function shouldDisplayMessage(message) {
    if (!currentChat.targetId) return false;

    if (message.type === 'private_message') {
        return currentChat.type === 'private' &&
               ((message.sender_id === currentChat.targetId && !message.is_own) ||
                (message.is_own && currentChat.targetId === message.receiver_id));
    } else if (message.type === 'group_message') {
        return currentChat.type === 'group' && currentChat.targetId == message.group_id;
    }

    return false;
}

/**
 * 添加消息到聊天界面
 */
function appendMessageToChat(message) {
    const messagesContainer = document.getElementById('chat-messages');

    // 移除空状态
    const emptyState = messagesContainer.querySelector('.empty-chat-state');
    if (emptyState) {
        emptyState.remove();
    }

    // 移除临时消息（如果有）
    if (message.is_own && !message.is_temporary) {
        const tempMsg = document.querySelector(`[data-message-id^="temp_"]`);
        if (tempMsg) {
            tempMsg.remove();
        }
    }

    const messageElement = createMessageElement(message);
    messagesContainer.appendChild(messageElement);
}

/**
 * 创建消息元素
 */
function createMessageElement(message) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message-group';
    messageDiv.setAttribute('data-message-id', message.message_id);

    const isOwn = message.is_own;
    const messageTime = new Date(message.created_at);

    let html = '';

    // 群聊显示发送者信息
    if (message.type === 'group_message' && !isOwn) {
        html += `
            <div class="message-group-header">
                <img src="${message.sender_avatar}" alt="头像" class="message-group-avatar"
                    onerror="this.src='/static/images/default-avatar.png'">
                <span class="message-group-sender">${message.sender_name}</span>
                <span class="message-group-time">${formatMessageTime(message.created_at)}</span>
            </div>
        `;
    }

    html += `
        <div class="message-bubble ${isOwn ? 'own' : 'other'}">
            ${message.content}
            <div class="message-time">${formatMessageTime(message.created_at)}</div>
            ${isOwn ? `
                <div class="message-status" id="status-${message.message_id}">
                    <i class="fas fa-check${message.is_read ? '-double text-primary' : ''}"></i>
                </div>
            ` : ''}
        </div>
    `;

    messageDiv.innerHTML = html;
    return messageDiv;
}

/**
 * 处理输入指示器
 */
function handleTypingIndicator(data) {
    const typingElement = document.getElementById('typing-indicator');

    if (!typingElement) return;

    if (data.is_typing &&
        ((data.target_type === 'private' && data.sender_id === currentChat.targetId) ||
         (data.target_type === 'group' && data.target_id == currentChat.targetId))) {

        typingElement.innerHTML = `
            <div class="message-bubble other">
                <div class="typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
                <div class="message-time">${data.sender_name} 正在输入...</div>
            </div>
        `;
        typingElement.style.display = 'block';

        // 滚动到底部
        setTimeout(() => {
            const messagesContainer = document.getElementById('chat-messages');
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }, 100);
    } else {
        typingElement.style.display = 'none';
    }
}

/**
 * 处理已读回执
 */
function handleReadReceipt(data) {
    const statusElement = document.getElementById(`status-${data.message_id}`);
    if (statusElement) {
        statusElement.innerHTML = '<i class="fas fa-check-double text-primary"></i> 已读';
    }
}

/**
 * 处理用户状态
 */
function handleUserStatus(data) {
    // 更新用户在线状态指示器
    const statusElements = document.querySelectorAll(`[data-user-id="${data.user_id}"] .chat-item-status`);
    statusElements.forEach(element => {
        element.classList.toggle('offline', data.status === 'offline');
    });
}

/**
 * 发送消息（WebSocket）
 */
function sendChatMessage() {
    const messageInput = document.getElementById('chat-message-input');
    const content = messageInput.value.trim();

    if (!content) {
        showMessage('请输入消息内容', 'warning');
        return;
    }

    if (!currentChat.targetId) {
        showMessage('请先选择聊天', 'warning');
        return;
    }

    // 优先使用WebSocket，失败时降级到HTTP
    if (checkWebSocketConnection()) {
        let messageData = {};

        if (currentChat.type === 'private') {
            messageData = {
                'type': 'private_message',
                'receiver_id': currentChat.targetId,
                'content': content
            };
        } else if (currentChat.type === 'group') {
            messageData = {
                'type': 'group_message',
                'group_id': currentChat.targetId,
                'content': content
            };
        }

        try {
            chatSocket.send(JSON.stringify(messageData));

            // 清空输入框
            messageInput.value = '';
            messageInput.style.height = 'auto';

            // 停止输入指示器
            sendTypingIndicator(false);

        } catch (error) {
            console.error('WebSocket发送失败，尝试HTTP:', error);
            sendChatMessageHTTP(content);
        }
    } else {
        console.log('WebSocket未就绪，使用HTTP发送');
        sendChatMessageHTTP(content);
    }
}

/**
 * 发送输入指示器
 */
function sendTypingIndicator(isTyping) {
    if (chatSocket && chatSocket.readyState === WebSocket.OPEN && currentChat.targetId) {
        const typingData = {
            'type': 'typing',
            'target_type': currentChat.type,
            'target_id': currentChat.targetId,
            'is_typing': isTyping
        };
        chatSocket.send(JSON.stringify(typingData));
    }
}

/**
 * 发送已读回执
 */
function sendReadReceipt(messageId, messageType) {
    if (chatSocket && chatSocket.readyState === WebSocket.OPEN) {
        const receiptData = {
            'type': 'read_receipt',
            'message_id': messageId,
            'message_type': messageType
        };
        chatSocket.send(JSON.stringify(receiptData));
    }
}

// 在页面加载时连接 WebSocket
document.addEventListener('DOMContentLoaded', function() {
    // 初始化聊天页面
    initializeChatPage();


    // 设置消息输入框事件
    const messageInput = document.getElementById('chat-message-input');
    if (messageInput) {
        let typingTimer;

        messageInput.addEventListener('input', function() {
            if (currentChat.targetId) {
                // 发送输入指示
                sendTypingIndicator(true);

                // 清除之前的定时器
                clearTimeout(typingTimer);

                // 设置定时器，1秒后停止输入指示
                typingTimer = setTimeout(() => {
                    sendTypingIndicator(false);
                }, 1000);
            }
        });

        messageInput.addEventListener('blur', function() {
            sendTypingIndicator(false);
        });
    }

    // 请求通知权限
    if ("Notification" in window && Notification.permission === "default") {
        Notification.requestPermission();
    }
});

/**
 * 通过 HTTP 发送消息（WebSocket 备用方案）
 */
async function sendChatMessageHTTP(content) {
    try {
        const response = await fetch('/user/send_chat_message/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCookie('csrftoken')
            },
            body: JSON.stringify({
                type: currentChat.type,
                target_id: currentChat.targetId,
                content: content
            })
        });

        const result = await response.json();

        if (result.success) {
            console.log('HTTP 消息发送成功:', result);
        } else {
            showMessage('发送失败: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('HTTP 消息发送失败:', error);
        showMessage('发送失败，请检查网络连接', 'error');
    }
}

// 在页面卸载时关闭连接
window.addEventListener('beforeunload', function() {
    if (chatSocket) {
        chatSocket.close(1000, "页面关闭");
    }
});
</script>
</body>
</html>
